import { defineStore } from 'pinia';
import { reactive, ref, computed } from 'vue';
import { useRouteStore } from '@/store';
import { fetchGetSaltInfo, fetchLogin, fetchRefreshToken, fetchLoginout } from '@/api/login';
import { AVATAR_PREVIEW_URL, fetchGetProfile } from '@/api/profile';

import crypto from '@/utils/crypto';
import { useNavigate } from '@/hooks/modules/router';

const userInfoState = {
  admin: '',
  key: '',
  userId: '',
  userName: '',
  avatar: '',
  roles: '',
  createBy: '',
  createTime: '',
  updateBy: '',
  updateTime: '',
  nickName: '',
  email: '',
  phoneNumber: '',
  sex: '',
  status: '',
  delFlag: '',
  loginIp: '',
  loginDate: '',
  statusName: ''
};

const useStore = defineStore(
  'user-store',
  () => {
    const routeStore = useRouteStore();
    const userInfo = reactive(userInfoState);
    const roles = ref([]);
    const menus = ref([]);
    const permissions = ref([]);
    const token = ref({ accessToken: '', refreshToken: '' });
    const isLogin = computed(() => !!token.value.accessToken);
    const navigate = useNavigate();
    const userAvatar = computed(() => {
      return userInfo.avatar ? `${AVATAR_PREVIEW_URL}/${userInfo.avatar}` : '';
    });

    function resetStore() {
      const store = useStore();
      store.$reset();
      store.$clearCache();
      routeStore.resetStore();
      navigate('/login');
    }

    async function loginByUserName(values) {
      const store = useStore();
      const { salt, uuid } = await fetchGetSaltInfo();
      values.uuid = uuid;
      values.userName = values.userName?.trim();
      values.password = crypto.encrypt(values.password, salt);
      Reflect.deleteProperty(values, 'remember');
      const res = await fetchLogin(values);
      store.$patch({ token: res });
      await this.getInfo();
      navigate('/');
    }

    async function refreshToken() {
      const store = useStore();
      const { refreshToken } = token.value;
      const res = await fetchRefreshToken(refreshToken);
      store.$patch({ token: res });
    }

    async function getInfo() {
      const store = useStore();
      const { user, menus, routers, permissions } = await fetchGetProfile();

      const roles = user.roles;
      store.$patch({ userInfo: user, roles, menus, permissions });
      routeStore.addDynamicRoutes(routers);
    }

    function updateUserInfo(data) {
      Object.keys(data).forEach((key) => {
        if (!data[key] && Object.prototype.toString.call(data[key]) !== '[object Number]') {
          delete data[key];
        }
      });
      const store = useStore();
      store.$patch({ userInfo: { ...userInfo, ...data } });
    }

    function logout() {
      fetchLoginout().finally(() => resetStore());
    }

    return {
      userAvatar,
      userInfo,
      token,
      roles,
      menus,
      permissions,
      isLogin,
      resetStore,
      loginByUserName,
      refreshToken,
      getInfo,
      updateUserInfo,
      logout
    };
  },
  {
    resetEnable: true, // 开启重置功能
    storage: {
      enable: true, // 开启存储功能
      key: 'user', // 存储的key
      aloneFields: true // 是否单独存储字段
    }
  }
);

export default useStore;
